<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use DateTime;
use Illuminate\Http\Request;
use OSS\OssClient;

class AliossController extends Controller
{
    /**
     * 获取oss上传参数
     *
     * @author hxq
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function get_oss_info(Request $request)
    {
        $id   = config('alioss.accessKeyId');
        $key  = config('alioss.accessKeySecret');
        $host = config('alioss.host');

        $now        = time();
        $expire     = 30; //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问
        $end        = $now + $expire;
        $expiration = $this->gmt_iso8601($end);
        $date       = date('Ymd');
        $object     = $request->get('object') ?: 'block_chain';
        $dir        = $object . '/' . $date . '/';

        //最大文件大小.用户可以自己设置
        $condition    = array(0 => 'content-length-range', 1 => 0, 2 => 1048576000);
        $conditions[] = $condition;

        //表示用户上传的数据,必须是以$dir开始, 不然上传会失败,这一步不是必项,只是为了安全起见,防止用户通过policy上传到别人的目录
        $start        = array(0 => 'starts-with', 1 => '$key', 2 => $dir);
        $conditions[] = $start;

        $arr = array('expiration' => $expiration, 'conditions' => $conditions);
        //echo json_encode($arr);
        //return;
        $policy         = json_encode($arr);
        $base64_policy  = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature      = base64_encode(hash_hmac('sha1', $string_to_sign, $key, true));

        $response              = array();
        $response['accessid']  = $id;
        $response['host']      = $host;
        $response['policy']    = $base64_policy;
        $response['signature'] = $signature;
        $response['expire']    = $end;
        //$response['callback'] = $base64_callback_body;
        //这个参数是设置用户上传指定的前缀
        $response['dir'] = $dir;
        echo json_encode($response);
    }

    protected function gmt_iso8601($time)
    {
        $dtStr      = date('c', $time);
        $mydatetime = new DateTime($dtStr);
        $expiration = $mydatetime->format(DateTime::ISO8601);
        $pos        = strpos($expiration, '+');
        $expiration = substr($expiration, 0, $pos);

        return $expiration . 'Z';
    }
    /**
     * 阿里云文件上传接口
     *
     * @author hxq
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function upload_file_to_oss(Request $request)
    {
        //阿里云操作类
        $oss = new OssClient(config('alioss.accessKeyId'), config('alioss.accessKeySecret'), config('alioss.endpoint'));
        //如果有image参数
        if ($request->has('image')) {
            //接收文件
            $image = $request->file('image');
            //文件路径变量
            $filePath = [];
            //遍历文件
            foreach ($image as $key => $value) {
                //文件验证成功
                if ($value->isValid()) {
                    //防止多次上传
                    if (!empty($value)) {
                        //临时文件的绝对路径
                        $realPath = $value->getRealPath();
                        // 扩展名
                        $ext = $value->getClientOriginalExtension();
                        //文件名
                        $filename = date('YmdHis') . '_' . uniqid() . '.' . $ext;
                        //oss路径
                        $osspath = 'block_chain/' . date('Ymd') .'/'. $filename;
                        //上传文件到阿里云
                        $oss->uploadFile(config('alioss.bucket'), $osspath, $realPath);
                        //判断对象是否存在
                        $does = $oss->doesObjectExist(config('alioss.bucket'), $osspath);
                        //oss文件不存在
                        if (!$does) {
                            //返回错误提示
                            return response()->json(['status' => 0, 'msg' => '文件上传oss失败']);
                        }
                        //写入数组
                        $filePath[$key] = $osspath;
                    }
                } else {
                    //验证失败
                    return respF(1038);
                }
            }
            //成功返回文件路径数组
            return response()->json(['status' => 1, 'msg' => '上传成功', 'data' => $filePath]);
        }
        //没有image，返回错误提示
        return respF(1011);
    }
}
